<?php
/**
 *生成订单ID
 */

class Merchant_Service_OrderIdService{
	private $serverId, $customerId, $time1;
	public function __construct($serverId = 'Q', $customerId = null){
		$this->serverId = $serverId;
		$this->time1 = $this->timeSlice();
		$this->customerId = $customerId?$customerId:$this->getUserLoginId();
	}
	public function getOrderId() {
		return strtoupper($this->serverId . $this->customerId . $this->time1 . $this->getSequence());
	}

	private function getOrderCnt() {
        $obj = new Merchant_Model_Customer();
		$db = $obj->getAdapter();
		$db->beginTransaction();
        $customer = $obj->getByValue($this->customerId);
		
		//if(isset($customer['customer_order_cnt'])){
		
            $date = date('Ymd');
            if(!empty($customer['customer_order_cnt'])){
                $arr = explode('-',$customer['customer_order_cnt']);
                if($date==$arr[0]){
                    $count = $arr[1]+1;
                }else{
                    $count = 1;
                }
            }else{
                $count = 1;
            }
            $update = array('customer_order_cnt'=>$date.'-'.$count);
            $obj->update($update,$this->customerId);
			
			
		$db->commit();	
		
        //}else{
         //   $count =1;
        //}
        return $count;
	}

	private function getSequence() {
		return sprintf('%04s', $this->getOrderCnt());
	}

	public function timeSlice() {
		return date('ymd');
	}

	public function getUserLoginId() {
        $obj = new Merchant_Service_Customer();
        $sessionUser= $obj->getLoginInfo();
        $customer = $sessionUser->customer;
        $customer_id = $customer['customer_id'];
        return $customer_id;
	}
}
//生成订单id 封装为静态函数
class Merchant_Service_OrderId{
	public static function getOrderId($serverId = 'Q', $userCode = null) {
		$order = new Merchant_Service_OrderIdService($serverId, $userCode);
//		echo $order->getOrderId();
		return $order->getOrderId();
	}
}
?>